package org.zhaya.sdk.processors.custom;

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import io.logz.sawmill.Doc;

import java.io.IOException;
import java.util.Map;

/**
 * used for ESB msg exchange demo.
 * <p>
 * Code logic:
 * extract the xml field with name 'xmlFieldName' to json object,
 * then add the json object as a new field with name 'xmlToJson';
 * <p>
 * Usage constrains:
 * Flowing terms are forbidden to use:
 * com.alibaba.fastjson.JSONObject;java.lang.System;java.lang.Runtime;while;do while;
 * <p>
 * Don't forget to import necessary classes.
 */
public class XmlToJsonPluginProcess {
    private static final String XML_FIELD_NAME = "xmlFieldName";
    private static final String XML_TO_JSON = "xmlToJson";
    private static final XmlMapper XML_MAPPER = new XmlMapper.Builder(new XmlMapper())
            .defaultUseWrapper(false)
            .enable(MapperFeature.USE_STD_BEAN_NAMING)
            .build();

    public void process(Doc doc) throws Exception {
        String xml = doc.getField(XML_FIELD_NAME).toString();
        Map<String, Object> map = xmlToObject(xml, Map.class);
        doc.addField(XML_TO_JSON, map);
    }

    public static <T> T xmlToObject(String xml, Class<T> clazz) throws IOException {
        return XML_MAPPER.readValue(xml, clazz);
    }
}
